package com.duolaibei.business.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.duolaibei.business.R;
import com.duolaibei.business.api.ApiName;
import com.duolaibei.business.base.BaseActivity;
import com.duolaibei.business.config.Preferences;
import com.duolaibei.business.http.HttpUtils;
import com.duolaibei.business.model.ResponseResult;
import com.duolaibei.business.model.WorkerData;
import com.duolaibei.business.utils.ACache;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.GsonUtil;
import com.duolaibei.business.utils.PreferenceUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.utils.log.LogDebug;
import com.duolaibei.business.view.App;
import com.duolaibei.business.view.dialog.TipDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xlm on 2017/11/9 0009
 */

public class WorkerManageActivity extends BaseActivity {

    @Inject(R.id.search)
    private RelativeLayout mLayoutSearch;
    @Inject(R.id.add)
    private RelativeLayout mLayoutAdd;
    @Inject(R.id.back)
    private RelativeLayout mLayoutBack;
    @Inject(R.id.title)
    private TextView mViewTitle;

    @Inject(R.id.search_add)
    private LinearLayout mLayoutSearchAdd;
    @Inject(R.id.reset)
    private RelativeLayout mLayoutReset;

    @Inject(R.id.worker_refresh)
    private SmartRefreshLayout mRefreshLayout;
    @Inject(R.id.worker_recycle)
    private RecyclerView mRecyclerView;
    private CommonAdapter<WorkerData.DataBeanX.DataBean> mCommonAdapter;
    private List<WorkerData.DataBeanX.DataBean> mBeanList;//员工列表
    private List<WorkerData.DataBeanX.DataBean> mShopListNew;//当前页员工列表
    private int pagesize = 5;
    private int pagenum = 1;
    private static final int MODE_QUERY = 1;
    private static final int MODE_REFRESH = 2;
    private static final int MODE_MORE = 3;
    private static int CURRENT_MODE = MODE_QUERY;

    private static final int SEARCH_CODE = 4;//搜索
    private static final int ADD_CODE = 5;//增加

    private String worker_uid;
    private String type;

    @Override
    protected void onGetIntent(Intent intent) {
        super.onGetIntent(intent);
        if (intent != null) {
            type = intent.getStringExtra("type");
        }
    }

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_workmanage_activity);
    }

    @Override
    protected void initViews() {
        mViewTitle.setText("员工管理");
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        if ("all".equals(type)) {
            getWorkerData();
            mLayoutSearchAdd.setVisibility(View.VISIBLE);
            mLayoutReset.setVisibility(View.GONE);//重置
        }
        setWorkerAdapter();
    }

    @Override
    protected void onSetListener() {
        mLayoutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                onRefreshData();
            }
        });
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (mShopListNew.size() == pagesize) {
                    pagenum++;
                    CURRENT_MODE = MODE_MORE;
                    getWorkerData();
                } else {
                    mRefreshLayout.setEnableLoadmore(false);
                }
            }
        });
        mLayoutSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索员工
                Intent intent = new Intent(getThis(), SearchWorkerActivity.class);
                startActivityForResult(intent, SEARCH_CODE);
            }
        });

        mLayoutAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //新增员工
                Intent intent = new Intent(getThis(), WorkerAddActivity.class);
                startActivityForResult(intent, ADD_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SEARCH_CODE:
                    type = data.getStringExtra("type");
                    mLayoutSearchAdd.setVisibility(View.GONE);
                    mLayoutReset.setVisibility(View.VISIBLE);
                    mLayoutReset.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            type = "all";
                            mLayoutSearchAdd.setVisibility(View.VISIBLE);
                            mLayoutReset.setVisibility(View.GONE);//重置
                            onRefreshData();
                        }
                    });
                    if ("part".equals(type)) {
                        worker_uid = data.getStringExtra("worker_uid");
                        pagesize = 5;
                        pagenum = 1;
                        //条件搜索
                        getWorkerData();
                        notifyDataRefresh();
                    }
                    break;
                case ADD_CODE:
                    type = data.getStringExtra("type");
                    mLayoutSearchAdd.setVisibility(View.VISIBLE);
                    mLayoutReset.setVisibility(View.GONE);
                    if ("all".equals(type)) {
                        onRefreshData();//刷新数据
                    }
                    break;
            }
        }
    }

    /**
     * 设置adapter
     */
    private void setWorkerAdapter() {
        mBeanList = new ArrayList<>();
        mCommonAdapter = new CommonAdapter<WorkerData.DataBeanX.DataBean>(getThis(),
                R.layout.item_worker_manage,
                mBeanList) {
            @Override
            protected void convert(ViewHolder holder, final WorkerData.DataBeanX.DataBean dataBean, int position) {
                holder.setText(R.id.shop_name, String.valueOf(dataBean.getNickname()));
                holder.setText(R.id.worker_num, String.format(getString(R.string.worker_1_s), dataBean.getUsername()));
                holder.setText(R.id.worker_mobile, String.format(getString(R.string.worker_2_s), dataBean.getMobile()));
                holder.setText(R.id.worker_uid, String.format(getString(R.string.worker_3_s), dataBean.getWorkmen_uid()));
                holder.setText(R.id.worker_id, String.valueOf(dataBean.getId()));
                holder.getView(R.id.worker_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showCardConfirm("确认删除吗?", String.valueOf(dataBean.getId()));
                    }
                });
            }
        };
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getThis()));
        mRecyclerView.setAdapter(mCommonAdapter);
    }

    private TipDialog confirmCardDialog;

    private void showCardConfirm(String txt, final String delete_id) {
        if (confirmCardDialog == null) {
            confirmCardDialog = new TipDialog(this);
        }
        confirmCardDialog.setContent(txt);
        confirmCardDialog.setCancelable(true);
        confirmCardDialog.setConfirm("确定");
        confirmCardDialog.show();
        confirmCardDialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                super.onConfirm();
                confirmCardDialog.dismiss();
                //删除员工
                deleteWorker(delete_id);
            }

            @Override
            public void onDismiss() {
                super.onDismiss();
                confirmCardDialog.dismiss();
            }
        });
    }

    /**
     * 删除员工
     */
    private void deleteWorker(String delete_id) {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.WORKER_DELETE);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("login_type", "merchant");
        param.add("delete_id", delete_id);
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().url(ApiName.API).params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(final String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToast(result.getInfo());
                    if (result.getStatus() == 1) {
                        //在当前页删除员工
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Message message = null;
                                try {
                                    JSONObject object = new JSONObject(string);
                                    JSONObject object1 = object.getJSONObject("data");
                                    message = Message.obtain();
                                    message.what = 111;
                                    message.obj = object1.optString("delete_id");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                if ("part".equals(type)) {
                                    onRefreshData();
                                } else {
                                    mHandler.sendMessage(message);
                                }
                            }
                        });
                    }
                } else {
                    showToast(string);
                }
            }
        });
    }

    //删除员工
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //退款操作
            if (msg.what == 111) {
                //可视范围内  item的具体下标(非回收后的)
                //首次 -1  -1
                int start = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
                        .findFirstVisibleItemPosition();
                int end = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
                        .findLastVisibleItemPosition();
                //可视范围内的数量
                for (int i = 0; i < mRecyclerView.getChildCount(); i++) {
                    if (start == -1) {
                        continue;
                    }
                    if (start >= end) {
                        break;
                    }
                    ViewGroup parent = (ViewGroup) mRecyclerView.getChildAt(i);
                    TextView delete_id = (TextView) parent.findViewById(R.id.worker_id);
                    if (String.valueOf(msg.obj).equals(String.valueOf(delete_id.getText().toString()))) {
                        for (WorkerData.DataBeanX.DataBean dataBean : mBeanList) {
                            if (String.valueOf(String.valueOf(delete_id.getText().toString())).equals(dataBean.getId())) {
                                LogDebug.d(String.valueOf(msg.obj));
                                LogDebug.d(String.valueOf(String.valueOf(delete_id.getText().toString())));
                                mBeanList.remove(dataBean);//删除员工
                                notifyDataRefresh();//更新显示数据
                                break;
                            }
                        }
                    }
                    start++;
                }
            }
        }
    };

    /**
     * 刷新列表界面
     */
    private void onRefreshData() {
        pagenum = 1;
        CURRENT_MODE = MODE_REFRESH;
        getWorkerData();
    }

    /**
     * 获取员工列表
     */
    private void getWorkerData() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.WORKERS);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("login_type", "merchant");
        param.add("current_page", String.valueOf(pagenum));
        param.add("page_size", String.valueOf(pagesize));
        if ("all".equals(type)) {
            LogDebug.d(type);
        } else if ("part".equals(type)) {
            if (!CommonUtil.isEmpty(worker_uid)) {
                param.add("workmen_uid", worker_uid);
            }
        }
        param.add("sign", param.getMd5String());
        showLoading("加载中");
        HttpUtils.getInstance().url(ApiName.API).params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissLoading();
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                    String jsonString = ACache.get(App.getApp()).getAsString(ApiName.WORKERS);
                    if (!CommonUtil.isEmpty(jsonString)) {
                        mBeanList.clear();
                        setTerminalData(jsonString, false);
                    }
                }
                if (mShopListNew.size() == pagesize) {
                    mRefreshLayout.setEnableLoadmore(true);
                } else {
                    mRefreshLayout.setEnableLoadmore(false);
                }
                switch (CURRENT_MODE) {
                    case MODE_QUERY:
                        break;
                    case MODE_REFRESH:
                        mRefreshLayout.finishRefresh(false);
                        break;
                    case MODE_MORE:
                        mRefreshLayout.finishLoadmore(false);
                        break;
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissLoading();
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (result.getStatus() == 1) {
                        setTerminalData(string, true);
                    } else {
                        showToast(result.getInfo());
                        mRefreshLayout.setEnableLoadmore(false);
                    }
                } else {
                    mRefreshLayout.setEnableLoadmore(false);
                    showToast(string);
                }

                switch (CURRENT_MODE) {
                    case MODE_QUERY:
                        break;
                    case MODE_REFRESH:
                        mRefreshLayout.finishRefresh(true);
                        break;
                    case MODE_MORE:
                        mRefreshLayout.finishLoadmore(true);
                        break;
                }
                if (mShopListNew.size() == pagesize) {
                    mRefreshLayout.setEnableLoadmore(true);
                } else {
                    mRefreshLayout.setEnableLoadmore(false);
                }

            }
        });
    }

    /**
     * 显示和保存数据
     *
     * @param string
     * @param save
     */
    private void setTerminalData(String string, boolean save) {
        final WorkerData data = GsonUtil.GsonToBean(string, WorkerData.class);
        List<WorkerData.DataBeanX.DataBean> dataBeanList = data.getData().getData();
        mShopListNew = dataBeanList;
        if (CURRENT_MODE != MODE_MORE) {
            if (mBeanList.size() != 0) {
                mBeanList.clear();
            }
        }
        if (dataBeanList.size() != 0) {
            mBeanList.addAll(dataBeanList);
        } else {
            mRefreshLayout.setEnableLoadmore(false);
        }
        notifyDataRefresh();
        if (save) {
            try {
                String json = GsonUtil.GsonString(mBeanList);
                JSONObject jsonObject = new JSONObject(string);
                JSONObject jsonObject1 = jsonObject.optJSONObject("data");
                JSONArray jsonArray = new JSONArray(json);
                jsonObject1.put("data", jsonArray);
                ACache.get(App.getApp()).put(ApiName.WORKERS, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 更新显示数据
     */
    private void notifyDataRefresh() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mCommonAdapter.notifyDataSetChanged();
            }
        });
    }


}
